<template>
 <div class="rating_page">
      <head-top head-title="兑换红包" :go-back=true></head-top>
   <section class="exchange">
     <yd-cell-group>
       <yd-cell-item>
         <yd-input slot="right" required  v-model="exchangeCode" max="11" placeholder="请输入兑换码"></yd-input>
       </yd-cell-item>
       <yd-cell-item>
         <span slot="left"> <input type="text" placeholder="验证码" maxlength="4" v-model="codeNumber"></span>
         <span slot="right">
                      <div class="img_change_img">
                      <img v-show="captchaCodeImg" :src="captchaCodeImg">
                      <div class="change_img" @click="getCaptchaCode">
                        <p>看不清</p>
                        <p class="changeOther">换一张</p>
                      </div>
                    </div>
            </span>
       </yd-cell-item>
     </yd-cell-group>
     <div class="yd-button" @click.stop="exchange">
       <button class="yd-btn-block " :class="{'yd-btn-primary':validStaue,'yd-btn-disabled':!validStaue}">兑换</button>
     </div>
   </section>
 </div>
</template>

<script type="text/ecmascript-6">
import headTop from 'components/header/head'
import {mapGetters} from 'vuex'
import {getcaptchas, exChangeHongbao} from 'src/service/getData'
  export default {
  data(){
     return{
       exchangeCode:'',
       codeNumber:'',
       captchaCodeImg: null
     }
   },
   created(){
    this.getCaptchaCode()
   },
   mounted(){
   },
   computed: {
     ...mapGetters(['userInfo']),
     validStaue(){
       let flag = (/^\d+$/gi.test(this.exchangeCode) && /^\w{4}$/gi.test(this.codeNumber));
       return flag;
     }
   },
   methods: {
     async getCaptchaCode(){
       let res = await getcaptchas();
       this.captchaCodeImg = res.code;
     },
   async  exchange(){
       if(this.validStaue){
         let res = await exChangeHongbao(this.userInfo.user_id, this.exchangeCode, this.codeNumber);
         //不成功则弹出提示框
         if (res.message) {
           this.getCaptchaCode();
           this.$dialog.toast({
             mes:res.message,
             timeout: 1000,
             icon: 'error',
           });
         }else{
           this.$dialog.alert({mes:'兑换成功'})
         }
       }
     }
   },
   components:{
    headTop
   }
  }
</script>
<style scoped lang="scss" rel="stylesheet/scss">
@import '../../../style/mixin';
.img_change_img{
  display: flex;
  align-items: center;
  padding:.3rem;
  img{
    display: inline-block;
  }
}
  .changeOther{
    color: $blue;
  }
</style>
